// stores/auth.ts
import { ref } from "vue";
import { defineStore } from "pinia";
import { jwtDecode } from "jwt-decode";

interface JwtPayload {
  loginId?: string;
  userId?: string;
  webId?: string;
  cusName?: string;
  typeId?: string;
  cusNo?: string;
  ifAuditStaff?: boolean;
  ifMaster?: boolean;
  ifPost?: boolean;
  shoppingNumber?: number;
  // Add other expected JWT payload fields here
}
//token过期时间
const TOKEN_EXPIRATION_HOURS = 24; // 默认24小时（相当于1天）
const MILLISECONDS_PER_HOUR = 60 * 60 * 1000; // 1小时的毫秒数

export const useUserStore = defineStore("user", () => {
  // State
  const userId = ref("");
  const ruserName = ref("");
  const loginId = ref("");
  const isLogin = ref(false); //弹框登录 模态框状态
  const token = ref(""); // Token 状态
  const tonkenExpires = ref(""); //Token过期时间
  const orderReview = ref(true); //订单审核权限
  const shoppingNumber = ref(0); //购物车物料数量

  // Actions
  const setUserId = (data: string) => {
    userId.value = data;
  };

  const setUser = (jwtToken: string) => {
    try {
      const decoded = jwtDecode<JwtPayload>(jwtToken);

      // Update state with decoded values
      if (decoded.loginId) loginId.value = decoded.loginId;
      if (decoded.userId) userId.value = decoded.userId;
      if (decoded.shoppingNumber) shoppingNumber.value = decoded.shoppingNumber;
      // Store the token
      setToken(jwtToken)
      isLogin.value = false;

      // You can add more fields from the decoded token as needed
      return decoded;
    } catch (error) {
      console.error("Failed to decode JWT:", error);
      isLogin.value = true;
      token.value = "";
      throw error;
    }
  };

  const setShoppingNumber = (num: number) => {
    shoppingNumber.value = num;
  };

  //修改登录状态
  const setIsLogin = (bol: boolean) => {
    isLogin.value = bol
  };

  //修改审批权限
  const setOrderReview = (bol: boolean) => {
    orderReview.value = bol;
  };

  // 封装 Token 操作方法（带 24 小时过期时间）
  const setToken = (newToken: string) => {
    token.value = newToken;
    // 记录设置时间（用于计算过期）
    tonkenExpires.value = String(Date.now()  + MILLISECONDS_PER_HOUR * TOKEN_EXPIRATION_HOURS);
  };

  //删除token
  const clearToken = () => {
    token.value = "";
    tonkenExpires.value = "";
  };

  // 检查 Token 是否有效
  const isValidToken = () => {
    if (!token.value) return false;
    return tonkenExpires.value && Date.now() < Number(tonkenExpires.value);
  };

  // 初始化时检查 Token 有效性
  if (!isValidToken()) {
    clearToken();
  }

  return {
    userId,
    orderReview,
    isLogin,
    token,
    setUser,
    setUserId,
    setIsLogin,
    setOrderReview,
    setToken,
    clearToken,
    isValidToken,
    setShoppingNumber,
  };
},
  {
    // Pinia 持久化插件配置
    persist: {
      pick: ["token", "userId", "tonken_expires"], // 只持久化 token,user
      // storage: localStorage,//默认localStorage  可选 sessionStorage
    },
  }
);
